package com.ruoyi.ams.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ruoyi.ams.domain.AmsAssetAllocation;
import com.ruoyi.ams.domain.AmsAssetAllocationDetail;
import com.ruoyi.ams.service.AmsReusingService;
import com.ruoyi.ams.service.IAmsAssetAllocationDetailService;
import com.ruoyi.ams.service.IAmsAssetAllocationService;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;

import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 资产调拨Controller
 * 
 * @author yfkj
 * @date 2022-05-16
 */
@RestController
@RequestMapping("/ams/allocation")
public class AmsAssetAllocationController extends BaseController
{
    @Autowired
    private IAmsAssetAllocationService amsAssetAllocationService;

    @Autowired
    private AmsReusingService amsReusingService;
    @Autowired
    private IAmsAssetAllocationDetailService assetAllocationDetailService;
//    @Autowired
//    private IAsmsAssetFullInfoService assetFullInfoService;
    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;

//    @Autowired
//    private RemoteUserService remoteUserService;
//    @Autowired
//    private RemoteDeptService remoteDeptService;
    @Autowired
    private SysUserController userController;
    @Autowired
    private SysDeptController deptController;

    @GetMapping("/test")
    public String test(){
        return "test";
    }
    /**
     * 查询资产调拨列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:allocation:list")
    @ApiOperation(value = "获取资产调拨列表")
    @GetMapping("/getAmsAssetAllocationList")
    public TableDataInfo getAmsAssetAllocationList(AmsAssetAllocation amsAssetAllocation)
    {
        QueryWrapper<AmsAssetAllocation> wrapper = new QueryWrapper<>();
        if (amsAssetAllocation.getStatus() != null) {
            wrapper.eq(AmsAssetAllocation.STATUS, amsAssetAllocation.getStatus());
        }
        wrapper.orderByDesc(AmsAssetAllocation.ALLOCATION_ID);
        startPage();
        List<AmsAssetAllocation> list = amsAssetAllocationService.list(wrapper);

        CompletableFuture<R<Map<Long, SysUser>>> future1 = CompletableFuture.supplyAsync(() ->
                userController.getAllUsers());

        CompletableFuture<R<Map<Long, SysDept>>> future2 = CompletableFuture.supplyAsync(() ->
                deptController.getAllDeptsMap());

        CompletableFuture<List<AsmsAssetFullInfo>> future4 = CompletableFuture.supplyAsync(() ->
                assetFullInfoService.list(new QueryWrapper<AsmsAssetFullInfo>()
                        .select(AsmsAssetFullInfo.ASSET_ID, AsmsAssetFullInfo.ASSET_TYPE_NAME)));

        List<AmsAssetAllocationDetail> allocationDetails = assetAllocationDetailService.list();

        HashMap<Long, String> assetInfoMap = new HashMap<>();
        R<Map<Long, SysUser>> allUsers = new R<>();
        R<Map<Long, SysDept>> allDeptsMap = new R<>();
        List<AsmsAssetFullInfo> fullInfos = new ArrayList<>();
        try {
            allUsers = future1.get();
            if (allUsers.getCode() == R.FAIL) {
                return amsReusingService.resovleError();
            }
            allDeptsMap = future2.get();
            if (allDeptsMap.getCode() == R.FAIL) {
                return amsReusingService.resovleError();
            }
            fullInfos = future4.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        for (AsmsAssetFullInfo fullInfo : fullInfos) {
            if (fullInfo != null) {
                assetInfoMap.put(fullInfo.getAssetId(), fullInfo.getAssetTypeName());
            }
        }

        Map<Long, SysUser> userMap = allUsers.getData();
        Map<Long, SysDept> deptMap = allDeptsMap.getData();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");

        for (AmsAssetAllocation allocation : list) {
            if (allocation.getOutDeptId() != null) {
                SysDept sysDept = deptMap.get(allocation.getOutDeptId());
                if (sysDept != null) {
                    allocation.setOutDeptName(sysDept.getDeptFullName());
                }
            }
            if (allocation.getOutUserId() != null) {
                SysUser sysUser = userMap.get(allocation.getOutUserId());
                if (sysUser != null) {
                    allocation.setOutUserName(sysUser.getNickName());
                }

            }
            if (allocation.getInDeptId() != null) {
                SysDept sysDept = deptMap.get(allocation.getInDeptId());
                if (sysDept != null) {
                    allocation.setInDeptName(sysDept.getDeptFullName());
                }
            }
            if (allocation.getInUserId() != null) {
                SysUser sysUser = userMap.get(allocation.getInUserId());
                if (sysUser != null) {
                    allocation.setInUserName(sysUser.getNickName());
                }
            }
            if (allocation.getOutTime() != null) {
                allocation.setOutTimeStr(fmt.format(new Date(allocation.getOutTime())));
            }
            if (allocation.getInTime() != null) {
                allocation.setInTimeStr(fmt.format(new Date(allocation.getInTime())));
            }
            if (allocation.getCreateTime() != null) {
                allocation.setCreateTimeStr(fmt.format(new Date(allocation.getCreateTime())));
            }
            if (allocation.getUpdateTime() != null) {
                allocation.setUpdateTimeStr(fmt.format(new Date(allocation.getUpdateTime())));
            }
            List<String> assetNames = new ArrayList<>();
            for (AmsAssetAllocationDetail allocationDetail : allocationDetails) {
                if (allocationDetail.getAllocationId().equals(allocation.getAllocationId())) {
                    String assetName = assetInfoMap.get(allocationDetail.getAssetId());
                    if (assetName != null) {
                        assetNames.add(assetName);
                    }
                }
            }
            allocation.setAssetNames(assetNames);
        }
        return getDataTable(list, 10);
    }


    /**
     * 获取资产调拨详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:allocation:query")
    //@ApiOperation(value = "获取资产调拨详情")
    @GetMapping(value = "/getAmsAssetAllocationById")
    public AjaxResult getAmsAssetAllocationById(@RequestParam("allocationId") Long allocationId)
    {
        return AjaxResult.success(amsAssetAllocationService.selectAmsAssetAllocationByAllocationId(allocationId));
    }

    /**
     * 新增资产调拨
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:allocation:add")
    @Log(title = "资产调拨", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增资产调拨")
    @PostMapping(value = "/addAmsAssetAllocation")
    public AjaxResult addAmsAssetAllocation(@RequestBody AmsAssetAllocation amsAssetAllocation)
    {
        //保存资产调拨信息
        amsAssetAllocation.setSn(amsReusingService.createSn());
        amsAssetAllocation.setCreateTime(System.currentTimeMillis());
        amsAssetAllocationService.save(amsAssetAllocation);

        //保存资产调拨详情信息
        if (amsAssetAllocation.getAssetIds().length == 0) {
            return AjaxResult.error("请至少选择一个资产");
        }
        List<AmsAssetAllocationDetail> allocationDetails = new ArrayList<>();
        for (Long assetId : amsAssetAllocation.getAssetIds()) {
            AmsAssetAllocationDetail allocationDetail = new AmsAssetAllocationDetail();
            allocationDetail.setAllocationId(amsAssetAllocation.getAllocationId());
            allocationDetail.setAssetId(assetId);
            allocationDetails.add(allocationDetail);
        }
        assetAllocationDetailService.saveBatch(allocationDetails);
        return AjaxResult.success();
    }

    /**
     * 修改资产调拨
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:allocation:edit")
    @Log(title = "资产调拨", businessType = BusinessType.UPDATE)
    //@ApiOperation(value = "修改资产调拨")
    @PostMapping(value = "/editAmsAssetAllocation")
    public AjaxResult editAmsAssetAllocation(@RequestBody AmsAssetAllocation amsAssetAllocation)
    {
        //修改资产调拨信息
        amsAssetAllocation.setUpdateTime(System.currentTimeMillis());
        amsAssetAllocationService.updateById(amsAssetAllocation);

        //修改资产调拨详情信息
        if (amsAssetAllocation.getAssetIds().length > 0) {
            //先删除之前存放的资产调拨详情
            assetAllocationDetailService.remove(new QueryWrapper<AmsAssetAllocationDetail>()
                    .eq(AmsAssetAllocationDetail.ALLOCATION_ID, amsAssetAllocation.getAllocationId()));
            //然后保存现在的资产调拨详情
            List<AmsAssetAllocationDetail> allocationDetails = new ArrayList<>();
            for (Long assetId : amsAssetAllocation.getAssetIds()) {
                AmsAssetAllocationDetail allocationDetail = new AmsAssetAllocationDetail();
                allocationDetail.setAllocationId(amsAssetAllocation.getAllocationId());
                allocationDetail.setAssetId(assetId);
                allocationDetails.add(allocationDetail);
            }
            assetAllocationDetailService.saveBatch(allocationDetails);
        }
        return AjaxResult.success();
    }

    /**
     * 删除资产调拨
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:allocation:remove")
    @Log(title = "资产调拨", businessType = BusinessType.DELETE)
	@GetMapping("/removeAmsAssetAllocations")
    public AjaxResult removeAmsAssetAllocations(@RequestParam Long[] allocationIds)
    {
        return toAjax(amsAssetAllocationService.deleteAmsAssetAllocationByAllocationIds(allocationIds));
    }
    @GetMapping("/getAmsAssetAllocationNamesForSelect")
    //@ApiOperation(value = "获取资产调拨名称列表用于下拉搜索")
    public AjaxResult getAmsAssetAllocationNamesForSelect()
    {
        List<AmsAssetAllocation> list = amsAssetAllocationService.list();//自行加条件
        List<KeyValueVo> resultList = new ArrayList<>();
        for (AmsAssetAllocation amsAssetAllocation: list ) {
            KeyValueVo vo = new KeyValueVo();
            //vo.setKey(it.getId());
            //vo.setValue(it.getName());
            resultList.add(vo);
        }
        return AjaxResult.success(resultList);
    }
    /**
     * 导出资产调拨列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:allocation:export")
    @Log(title = "资产调拨", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAmsAssetAllocation")
    public String exportAmsAssetAllocation(HttpServletResponse response, AmsAssetAllocation amsAssetAllocation) throws IOException
    {
        List<AmsAssetAllocation> list = amsAssetAllocationService.selectAmsAssetAllocationList(amsAssetAllocation);
        ExcelUtil<AmsAssetAllocation> util = new ExcelUtil<AmsAssetAllocation>(AmsAssetAllocation.class);
        util.exportExcel(response, list, "资产调拨数据");
        return "";
    }

}
